import {
  ModalForm,
  ProFormCheckbox,
  ProFormDigit,
  ProFormRadio,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import React, { useMemo } from 'react';
import { useModel } from 'umi';

import { Langs } from '@/services/consts';

type FormProps = {
  visible: boolean;
  current: API.Product | undefined;
  onCancel: () => void;
  onSubmit: (values: API.Product) => Promise<void>;
};

const Form: React.FC<FormProps> = (props) => {
  const { visible, current, onCancel, onSubmit } = props;
  if (!visible) {
    return null;
  }

  const { nextProductId } = useModel('useGlobalModel');

  let defaultCurrent: Partial<API.Product> | undefined = undefined;
  if (!current) {
    defaultCurrent = {
      id: nextProductId,
      langs: ['en-US', 'zh-CN', 'zh-TW'],
      defaultLang: 'en-US',
      status: true,
    };
  }

  const renderIdDom = useMemo(() => {
    if (current) {
      return <ProFormText name="id" label="ID" readonly={true} />;
    } else {
      return (
        <ProFormDigit
          name="id"
          label="ID"
          wrapperCol={{ span: 4 }}
          min={1001}
          max={999999}
        />
      );
    }
  }, [current]);

  return (
    <ModalForm<API.Product>
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      open={visible}
      initialValues={current ? current : defaultCurrent}
      //preserve={false}
      // trigger={<>{children}</>}
      title={`${current ? '编辑' : '添加'}产品`}
      width={640}
      onFinish={onSubmit}
      modalProps={{
        onCancel: onCancel,
        //destroyOnClose: true,
        maskClosable: false,
      }}
    >
      {renderIdDom}
      <ProFormText
        name="name"
        label="名称"
        rules={[{ required: true, message: '请输入名称' }]}
        placeholder="请输入名称"
      />
      <ProFormText
        name="domain"
        label="域名"
        rules={[{ required: true, message: '请输入域名' }]}
        placeholder="请输入域名"
      />
      <ProFormCheckbox.Group name="langs" label="支持语言" options={Langs} />
      <ProFormRadio.Group name="defaultLang" label="默认语言" options={Langs} />
      <ProFormSwitch
        name="status"
        label="状态"
        fieldProps={{
          defaultChecked: false,
        }}
      />
      <ProFormTextArea name="remark" label="备注" />
    </ModalForm>
  );
};

export default Form;
